#include "stdafx.h"
#include "Application.h"
#include "render/Surface.h"
#include "render/render.h"
#include "render/font.h"
#include "imgui/imgui.h"
#include "database/database.h"

Application::Application() 
{
	m_pFont = 0;
	m_pSection = 0;

	SetVideoMode(1024, 768);
	SetAppName("Database");
}

bool Application::OnInit() 
{
	m_pFont = Render::LoadFont("vera.ttf", 16);
	m_gui.Initialise();
	return true;
}

void Application::BeginSection()
{
	if (m_pSection->OnInit(this) == false)
	{
		delete m_pSection;
		m_pSection = 0;
	}

	if (m_pSection)
	{
		m_pSection->Activate();
	}
}

void Application::OnUpdate() 
{
	if (m_pSection && m_pSection->IsRunning())
	{
		m_pSection->OnUpdate(GetFrameTimeMs() / 1000.f);
	}
	else
	{
		delete m_pSection;
		m_pSection = 0;
	}
}

void Application::OnEvent(const App::Event* pEvent)
{
	if (m_pSection)
		m_pSection->OnEvent(pEvent);

	m_gui.OnEvent(pEvent);
}

void Application::RenderGui()
{
	Render::SetRenderTarget(MainView());
	Render::Clear(0x0);

	{
		Imgui::Frame frame(m_gui, MainView());
		Imgui::HorizontalList layout(m_gui, Imgui::FIT|Imgui::EMPTY|Imgui::BORDERLESS|Imgui::EXPAND);

		if (m_gui.DoButton("Quit"))
			OnExit();

		if (m_gui.DoButton("Database"))
		{
			Assert(m_pSection == 0);

			m_pSection = new Database;

			BeginSection();
		}
	}
}

void Application::OnRender() 
{
	if (m_pSection)
		m_pSection->OnRender(MainView());
	else
		RenderGui();

	{
		int width, height;
		GetVideoMode(width, height);

		int frameTime = (int) GetFrameTimeMs();
		int updateTime = (int) GetUpdateTimeMs();
		int renderTime = (int) GetRenderTimeMs();
		std::stringstream ss;
		ss << frameTime << "(" << updateTime << ", " << renderTime << ")";

		Render::DrawText(width - 150, height - 20, m_pFont, ss.str().c_str(), 0xffffffff);
	}
}

Application::~Application()
{
	OnCleanup();
}

void Application::OnCleanup() 
{
	Render::FreeFont(m_pFont);
	delete m_pSection;

	m_pFont = 0;
	m_pSection = 0;

	m_gui.Shutdown();
}
